﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyBlog.IService;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyBlog.WebAPI.JWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        private readonly IWriterInfoService writerInfoService;

        public AuthoizeController(IWriterInfoService writerInfoService)
        {
            this.writerInfoService = writerInfoService;
        }
        [HttpPost("Login")]
        public async Task<ApiResult> Login(string userName, string userPwd)
        {
            string pwd = MD5Helper.MD5Encrypt32(userPwd);
            var witer = await writerInfoService.FindAsync(c => c.UserName == userName && c.UserPwd == pwd);

            if (witer == null) return ApiResultHelper.Error("账号或密码错误");

            var claims = new Claim[] {
                new(ClaimTypes.Name, witer.Name),
                new("Id",witer.Id.ToString()),
                new("UserName",witer.UserName)
            };//相当于身份证
            //秘钥，最少16位 
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));

            var token = new JwtSecurityToken(
                issuer: "http://localhost:6060",//代表办法Token的Web应用程序
                audience: "http://localhost:5000",//Token的受理者
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(1),//过期时间
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            var jwtToken=new JwtSecurityTokenHandler().WriteToken(token);
            return ApiResultHelper.Success(jwtToken);
        }

    }
}
